#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
图标转换脚本
将SVG图标转换为不同平台和尺寸的图标格式
"""

import os
import sys
from pathlib import Path
from typing import List, Tuple

# macOS Cairo 库路径设置
if sys.platform == 'darwin':
    # 设置 Cairo 库路径
    cairo_paths = [
        '/opt/homebrew/lib',  # Apple Silicon Homebrew
        '/usr/local/lib',     # Intel Homebrew
        '/opt/local/lib',     # MacPorts
    ]
    
    # 找到第一个存在的路径
    for cairo_path in cairo_paths:
        if os.path.exists(os.path.join(cairo_path, 'libcairo.2.dylib')):
            print(f"发现 Cairo 库: {cairo_path}")
            # 设置环境变量
            if 'DYLD_LIBRARY_PATH' in os.environ:
                os.environ['DYLD_LIBRARY_PATH'] = f"{cairo_path}:{os.environ['DYLD_LIBRARY_PATH']}"
            else:
                os.environ['DYLD_LIBRARY_PATH'] = cairo_path
            break
    else:
        print("警告: 未找到 Cairo 库，可能需要安装:")
        print("  brew install cairo")

try:
    from PIL import Image, ImageDraw
    import cairosvg
except ImportError as e:
    print(f"缺少必要的依赖包: {e}")
    print("请运行: pip install Pillow cairosvg")
    if sys.platform == 'darwin':
        print("在 macOS 上还需要: brew install cairo")
    sys.exit(1)


class IconConverter:
    """图标转换器"""
    
    def __init__(self, svg_path: str, output_dir: str):
        """初始化转换器
        
        Args:
            svg_path: SVG文件路径
            output_dir: 输出目录
        """
        self.svg_path = Path(svg_path)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        # 定义各平台需要的尺寸
        self.sizes = {
            'ico': [16, 24, 32, 48, 64, 128, 256],  # Windows ICO
            'icns': [16, 32, 64, 128, 256, 512, 1024],  # macOS ICNS
            'png': [16, 24, 32, 48, 64, 96, 128, 192, 256, 512]  # 通用PNG
        }
    
    def svg_to_png(self, size: int) -> Image.Image:
        """将SVG转换为指定尺寸的PNG图像
        
        Args:
            size: 目标尺寸
            
        Returns:
            PIL Image对象
        """
        # 使用cairosvg将SVG转换为PNG数据
        png_data = cairosvg.svg2png(
            url=str(self.svg_path),
            output_width=size,
            output_height=size
        )
        
        # 从PNG数据创建PIL Image
        from io import BytesIO
        return Image.open(BytesIO(png_data)).convert("RGBA")
    
    def create_ico(self, output_path: str):
        """创建Windows ICO文件
        
        Args:
            output_path: 输出文件路径
        """
        print(f"创建 Windows ICO: {output_path}")
        
        # 生成不同尺寸的图像
        images = []
        for size in self.sizes['ico']:
            try:
                img = self.svg_to_png(size)
                images.append(img)
                print(f"  - 生成 {size}x{size} 图像")
            except Exception as e:
                print(f"  - 警告: 无法生成 {size}x{size} 图像: {e}")
        
        if images:
            # 保存为ICO文件
            images[0].save(
                output_path,
                format='ICO',
                sizes=[(img.width, img.height) for img in images],
                append_images=images[1:]
            )
            print(f"  ✓ ICO文件已创建: {output_path}")
        else:
            print(f"  ✗ 无法创建ICO文件")
    
    def create_icns(self, output_path: str):
        """创建macOS ICNS文件
        
        Args:
            output_path: 输出文件路径
        """
        print(f"创建 macOS ICNS: {output_path}")
        
        # 创建临时目录存放iconset
        import tempfile
        import shutil
        
        with tempfile.TemporaryDirectory() as temp_dir:
            iconset_dir = Path(temp_dir) / "icon.iconset"
            iconset_dir.mkdir()
            
            # ICNS规格映射
            icns_mapping = {
                16: ["icon_16x16.png"],
                32: ["icon_16x16@2x.png", "icon_32x32.png"],
                64: ["icon_32x32@2x.png"],
                128: ["icon_128x128.png"],
                256: ["icon_128x128@2x.png", "icon_256x256.png"],
                512: ["icon_256x256@2x.png", "icon_512x512.png"],
                1024: ["icon_512x512@2x.png"]
            }
            
            # 生成所需的PNG文件
            success_count = 0
            for size in self.sizes['icns']:
                try:
                    img = self.svg_to_png(size)
                    
                    # 根据映射保存文件
                    if size in icns_mapping:
                        for filename in icns_mapping[size]:
                            file_path = iconset_dir / filename
                            img.save(file_path, format='PNG')
                            print(f"  - 生成 {filename}")
                            success_count += 1
                            
                except Exception as e:
                    print(f"  - 警告: 无法生成 {size}x{size} 图像: {e}")
            
            if success_count > 0:
                # 使用iconutil创建ICNS文件 (需要macOS)
                import subprocess
                try:
                    subprocess.run([
                        'iconutil', '-c', 'icns', 
                        str(iconset_dir), 
                        '-o', str(output_path)
                    ], check=True, capture_output=True)
                    print(f"  ✓ ICNS文件已创建: {output_path}")
                except (subprocess.CalledProcessError, FileNotFoundError):
                    print(f"  ⚠ iconutil不可用，将创建备用PNG文件")
                    # 备用方案：直接保存最大尺寸的PNG
                    backup_path = Path(output_path).with_suffix('.png')
                    img_512 = self.svg_to_png(512)
                    img_512.save(backup_path, format='PNG')
                    print(f"  ✓ 备用PNG文件已创建: {backup_path}")
            else:
                print(f"  ✗ 无法创建ICNS文件")
    
    def create_png_set(self, output_dir: str):
        """创建PNG图标集
        
        Args:
            output_dir: 输出目录
        """
        print(f"创建 PNG 图标集: {output_dir}")
        
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        for size in self.sizes['png']:
            try:
                img = self.svg_to_png(size)
                png_path = output_path / f"icon_{size}x{size}.png"
                img.save(png_path, format='PNG')
                print(f"  - 生成 {png_path.name}")
            except Exception as e:
                print(f"  - 警告: 无法生成 {size}x{size} 图像: {e}")
        
        print(f"  ✓ PNG图标集已创建")
    
    def create_all_formats(self):
        """创建所有格式的图标"""
        print("开始转换图标...")
        print(f"源文件: {self.svg_path}")
        print(f"输出目录: {self.output_dir}")
        print("-" * 50)
        
        # 创建Windows ICO
        ico_path = self.output_dir / "icon.ico"
        self.create_ico(str(ico_path))
        
        print()
        
        # 创建macOS ICNS
        icns_path = self.output_dir / "icon.icns"
        self.create_icns(str(icns_path))
        
        print()
        
        # 创建PNG图标集
        png_dir = self.output_dir / "png"
        self.create_png_set(str(png_dir))
        
        print()
        print("=" * 50)
        print("图标转换完成！")
        print(f"输出文件位置: {self.output_dir}")


def main():
    """主函数"""
    # 检查SVG文件是否存在
    svg_path = Path(__file__).parent.parent / "assets" / "icon.svg"
    if not svg_path.exists():
        print(f"错误: 找不到SVG文件: {svg_path}")
        sys.exit(1)
    
    # 输出目录
    output_dir = Path(__file__).parent.parent / "assets" / "icons"
    
    # 创建转换器并执行转换
    converter = IconConverter(str(svg_path), str(output_dir))
    converter.create_all_formats()


if __name__ == "__main__":
    main() 